#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:Venus
@file:数据集分析学习.py
@time:2021/11/29/21：56
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns


if __name__ == '__main__':
    # 1
    color = sns.color_palette()
    pd.set_option('precision', 3)
    dataPath = r'C:\Users\Venus\Desktop\Pycharm_Workspace\venv\智能优化方法\大作业\data\winequality-red.csv'
    df = pd.read_csv(r"C:\Users\Venus\Desktop\Pycharm_Workspace\venv\智能优化方法\大作业\data\winequality-red.csv", sep=';')
    # print(df.head(5))
    # 2
    # print(df.info())
    # 3
    # print(df.describe())
    # 4
    plt.style.use('ggplot')
    colnm = df.columns.tolist()
    fig = plt.figure(figsize=(8, 6))
    for i in range(12):
        plt.subplot(2, 6, i + 1)
        #     sns.boxplot(df[colnm[i]],orient='v',width=1,color=color[4])  # 过时语法
        sns.boxplot(x=None, y=df[colnm[i]], color=color[9])
        plt.ylabel(colnm[i], fontsize=12)
    plt.tight_layout()
    plt.title('Figure 1:Univariate BoxPlots')
    plt.show()
    # print('\nFigure 1:Univariate BoxPlots')
    # 5
    colnm = df.columns.tolist()
    plt.figure(figsize=(10, 8))
    for i in range(12):
        plt.subplot(4, 3, i + 1)
        df[colnm[i]].hist(bins=100, color=color[8])
        plt.xlabel(colnm[i], fontsize=12)
        plt.ylabel('Frequency')
    plt.tight_layout()  # 防止重叠
    plt.title('Figure 2: Univariate Histograms')
    plt.show()
    # 6
    acidityFeat = ['fixed acidity', 'volatile acidity', 'citric acid', 'free sulfur dioxide', 'total sulfur dioxide',
                   'sulphates']
    plt.figure(figsize=(10, 4))
    for i in range(6):
        ax = plt.subplot(2, 3, i + 1)
        v = np.log10(np.clip(df[acidityFeat[i]].values, a_min=0.001, a_max=None))
        plt.hist(v, bins=50, color=color[5])
        plt.xlabel('log(' + acidityFeat[i] + ')', fontsize=12)
        plt.ylabel('Frequency')
    plt.tight_layout()
    plt.title("Figure 3: Acidity Features in log10 Scale")
    plt.show()
    # 7
    plt.figure(figsize=(6, 3))
    bins = 10 ** (np.linspace(-2, 2))
    plt.hist(df['fixed acidity'], bins=bins, edgecolor='k', label='Fixed Acidity')
    plt.hist(df['volatile acidity'], bins=bins, edgecolor='k', label='Volatitle Acidity')
    plt.hist(df['citric acid'], bins=bins, edgecolor='k', label='Citric Acid')
    plt.xscale('log')
    plt.xlabel('Acid Concentration(g/dm^3)')
    plt.ylabel('Frequency')
    plt.title('Histogram of Acid Contacts')
    plt.legend()
    plt.tight_layout()
    plt.show()
    # 8
    df['total acid'] = df['fixed acidity'] + df['volatile acidity'] + df['citric acid']
    plt.figure(figsize=(8, 3))
    plt.subplot(1, 2, 1)
    plt.hist(df['total acid'], bins=50, color=color[0])
    plt.xlabel('total acid')
    plt.ylabel('Frequency')
    plt.subplot(122)
    plt.hist(np.log(df['total acid']), bins=50, color=color[3])
    plt.xlabel('log(total acid)')
    plt.ylabel('Frequency')
    plt.tight_layout()
    plt.show()
    print("Figure 5: Total Acid Histogram")
    # 9
    df['sweetness'] = pd.cut(df['residual sugar'], bins=[0, 4, 12, 45, 999],
                             labels=["dry", "medium dry", "semi-sweet", "sweet"])
    plt.figure(figsize=(5, 3))
    df['sweetness'].value_counts().plot(kind='bar', color=color[2])
    plt.xticks(rotation=0)  # rotation代表lable显示的旋转角度。
    # plt.yticks(rotation=90)
    plt.xlabel('sweetness', fontsize=12)  # fontsize文字大小
    plt.ylabel('Frequency', fontsize=12)
    plt.tight_layout()
    plt.show()
    print("Figure 6:Sweetness")
    # 10
    sns.set_style('ticks')  # 设置图表主题背景为十字叉
    sns.set_context("paper", font_scale=1.1)  # 设置图表样式
    colnm = df.columns.tolist()[:11] + ['total acid']
    plt.figure(figsize=(10, 8))
    for i in range(12):
        plt.subplot(4, 3, i + 1)
        sns.boxplot(x='quality', y=colnm[i], data=df, color=color[1], width=0.6)
        plt.ylabel(colnm[i], fontsize=12)
    plt.tight_layout()
    plt.show()
    print("\nFigure 7: Physicochemical Properties and Wine Quality by Boxplot")
    # 11
    sns.set_style("dark")
    plt.figure(figsize=(10, 8))
    colnm = df.columns.tolist()[:11] + ['total acid', 'quality']
    mcorr = df[colnm].corr()  # 相关系数矩阵，即给出了任意两个变量之间的相关系数
    mask = np.zeros_like(mcorr, dtype=np.bool)  # 创建一个mcorr一样的全False矩阵
    mask[np.triu_indices_from(mask)] = True  # 上三角置位True
    cmap = sns.diverging_palette(150, 10, as_cmap=True)  # 建立一个发散调色板
    g = sns.heatmap(mcorr, mask=mask, cmap=cmap, square=True, annot=True, fmt='0.2f')
    plt.show()
    print("\nFigure 8:Pairwise Correlation Plot")
    # 12
    print(mcorr)
    # 13
    sns.set_style('ticks')
    sns.set_context("notebook", font_scale=1.4)
    plt.figure(figsize=(6, 4))  # 画出双变量的散点图，然后以y~x拟合回归方程和预测值95%置信区间并将其画出。
    sns.regplot(x='density', y='alcohol', data=df, scatter_kws={'s': 10}, color=color[2])
    plt.xlim(0.989, 1.005)
    plt.ylim(7, 16)
    plt.show()
    print("Figure 9: Density vs Alcohol")
    # 14
    acidity_related = ['fixed acidity', 'volatile acidity', 'total sulfur dioxide',
                       'sulphates', 'total acid']
    plt.figure(figsize=(10, 6))
    for i in range(5):
        plt.subplot(2, 3, i + 1)
        sns.regplot(x='pH', y=acidity_related[i], data=df, scatter_kws={'s': 10}, color=color[1])
    plt.tight_layout()
    plt.show()
    print("Figure 10: pH vs acid")
    # 15
    plt.style.use('ggplot')
    sns.lmplot(x='alcohol', y='volatile acidity', hue='quality', data=df, fit_reg=False, scatter_kws={'s': 10},
               height=4)
    plt.show()
    print("Figure 11-1: Scatter Plots of Alcohol, Volatile Acid and Quality")
    # 16
    sns.lmplot(x='alcohol', y='volatile acidity', col='quality', hue='quality', data=df, fit_reg=False, height=3,
               aspect=0.9, col_wrap=3, scatter_kws={'s': 20})
    plt.show()
    print("Figure 11-2: Scatter Plots of Alcohol, Volatile Acid and Quality")
    # 17
    sns.set_style('ticks')
    sns.set_context("notebook", font_scale=1.4)
    plt.figure(figsize=(6, 5))
    cm = plt.cm.get_cmap('RdBu')
    sc = plt.scatter(df['fixed acidity'], df['citric acid'], c=df['pH'], vmin=2.6, vmax=4, s=15, cmap=cm)
    bar = plt.colorbar(sc)
    bar.set_label('pH', rotation=0)
    plt.xlabel('fixed acidity')
    plt.ylabel('citric acid')
    plt.xlim(4, 18)
    plt.ylim(0, 1)
    plt.show()
    print('Figure 12: pH with Fixed Acidity and Citric Acid')
